import { createSlice } from "@reduxjs/toolkit"
import http from "../../utils/http"
import { setToken,getToken } from "../../utils/token"
import { clearToken } from "../../utils/token"
export const login = createSlice({
    name: "login",
    initialState: {
        token:getToken()||'',
    },
    reducers: {
        // action函数（同步）
        setTokenRd: (state,action) => {
            state.token = action.payload;
        },
        delTokenRd: (state) => {
            state.token = ''
        },
    },
})
export function logoutAction(){
    return (dispatch) => {
        //删除token和用户信息
        dispatch(delTokenRd())
        clearToken()
    }
}
//异步action函数
export function loginAction(value) {
    return async (dispatch) => {
        const {data,message} = await http.post('/authorizations',value)
        if(message === 'OK'){
            dispatch(setTokenRd(data.token))
            setToken(data.token)
        }else{
            alert(data.message)
        }
    }
}
//导出
export const { setTokenRd,delTokenRd } = login.actions
export default login.reducer